<?php
namespace App\Logic\Spider;

use Illuminate\Support\Arr;
use QL\QueryList;
class CrawlReviews extends CrawlCommon
{
    public static function reviews($url,$asin){
        $header = self::$_header;
        $header['User-Agent'] = Arr::random(self::$_userAgent);
        try{
            $ql = QueryList::get($url.$asin,null,[
                'timeout' => 30,
                'headers' => $header
            ]);
            $re = self::_getReviewsDefault($ql);
            $ql->destruct();
            return $re;
        }catch(\Exception $e){
            return ['star' => $e->getCode(),'ratings' => '','b_rank' => $e->getMessage(),'s_rank' => ''];
        }
    }

    private static function _getReviewsDefault(QueryList $ql){
        $_star = $ql->find('#acrPopover')->attr('title');
        $star = self::__formReviews($_star);
        $_ratings = $ql->find('#acrCustomerReviewText')->text();
        $ratings = self::__formRatings($_ratings);
        $_rank = $ql->find('#acrPopover')->parents('tr')->next()->find('td')->text();
        if(('no star' != $star) && empty($_rank)){
            $_rank = $ql->find('#acrPopover')->parents('ul')->prev()->text();
        }
        $rank = self::__formRank($_rank);
        return ['star' => $star,'ratings' => $ratings,'b_rank' => $rank['b_rank'],'s_rank' => $rank['s_rank']];
    }

    private static function __formReviews($star){
        if(empty($star)){
            return 'no star';
        }else{
            return str_replace(',','.',substr($star,0,3));
        }
    }

    private static function __formRatings($ratings){
        if(empty($ratings)){
            return 'no ratings';
        }else{
            $str1 = ltrim($ratings);
            $str2 = str_replace(["\n","\r","\r\n"],"\n",$str1);
            $arr1 = explode("\n",$str2);
            if(!empty($arr1)){
                $arr2 = explode(" ",$arr1[0]);
                if(!empty($arr2)){
                    return $arr2[0];
                }
            }
            return 'no match ratings';
        }
    }

    private static function __formRank($rank){
        if(empty($rank)){
            return ['b_rank' => 'no rank','s_rank' => ''];
        }else{
            $rank = self::__replaceRank($rank);
            $bPos = stripos($rank,'(');
            if(!$bPos){
                return ['b_rank' => trim($rank),'s_rank' => ''];
            }else{
                $bRank = trim(substr($rank,0,$bPos - 1));
                $sPos = stripos($rank,')');
                if(!$sPos){
                    return ['b_rank' => $bRank,'s_rank' => ''];
                }else{
                    $sRank = trim(substr($rank,$sPos + 1));
                    return ['b_rank' => $bRank,'s_rank' => $sRank];
                }
            }
        }
    }

    private static function __replaceRank($rank){
        $search = ["Best Sellers Rank:",
            'Amazon Bestseller-Rang:',
            "ClasificaciÃ³n en los mÃ¡s vendidos de Amazon:",
            "Posizione nella classifica Bestseller di Amazon:",
            "Classement des meilleures ventes d'Amazon :"];
        return str_replace($search,'',$rank);
    }

    private static function _getReviews(QueryList $ql){
//        dd($ql->getHtml());
        $fileDir = 'app'.DIRECTORY_SEPARATOR.'operation'.DIRECTORY_SEPARATOR.'crawl'.DIRECTORY_SEPARATOR.'reviews';
        $file = storage_path($fileDir).DIRECTORY_SEPARATOR.'test-fr.html';
        $fp = fopen($file, 'a');
//        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
//        fwrite($fp, $ql->getHtml());
        $fp = fopen($file, 'r');
        $body = '';
        while(!feof($fp)){
            $body .= fgets($fp);
        }
        fclose($fp);
//        $reviews = $ql->html($body)->find('#acrPopover')->attr('title');dd($reviews);
        $reviews = $ql->html($body)->find('#productDetails_detailBullets_sections1>tr:eq(2)>td')->text();dd($reviews);
//        $reviews = $ql->html($body)->range('#productDetails_detailBullets_sections1>tr:eq(2)')->queryData();dd($reviews);
        dd(1);
        return ['reviews' => empty($reviews) ? 'no review' : $reviews,'rank' => ''];
    }

}
